package com.ls.event;

import com.alibaba.fastjson.JSON;
import com.ls.entity.DiscussPost;
import com.ls.entity.Event;
import com.ls.entity.Message;
import com.ls.entity.User;
import com.ls.service.DiscussPostService;
import com.ls.service.ElasticsearchService;
import com.ls.service.MessageService;
import com.ls.service.UserService;
import com.ls.util.CommunityConstant;
import com.ls.util.MailClient;
import com.ls.util.R;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 系统消息事件消费者
 *
 * @author ls
 * @date 2021/1/31
 **/
@Component
public class EventConsumer implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.command}")
    private String wkImageCommand;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.share.name}")
    private String shareBucketName;

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleMessage(ConsumerRecord consumerRecord) {
        Event event = checkParseEvent(consumerRecord);
        if (event == null) {
            return;
        }

        // 发送系统消息
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        if (!event.getData().isEmpty()) {
            content.putAll(event.getData());
        }

        message.setContent(JSON.toJSONString(content));
        messageService.addMessage(message);
    }

    private Event checkParseEvent(ConsumerRecord consumerRecord) {
        if (consumerRecord == null || consumerRecord.value() == null) {
            logger.error("消息的内容为空!");
            return null;
        }
        Event event = JSON.parseObject(consumerRecord.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息格式错误!");
            return null;
        }
        return event;
    }

    /**
     * 功能描述: <br>
     * 消费发帖事件
     *
     * @param consumerRecord
     * @author ls
     * @date 2021/8/21 20:12
     */
    @KafkaListener(topics = TOPIC_PUBLISH)
    public void handlePublishMessage(ConsumerRecord consumerRecord) {
        Event event = checkParseEvent(consumerRecord);
        if (event == null) {
            return;
        }

        DiscussPost discussPost = discussPostService.queryDiscussPostById(event.getEntityId());
        // 保存更新 帖子到 es 中
        elasticsearchService.saveDiscussPost(discussPost);

    }

    /**
     * 功能描述: <br>
     * 消费删帖事件
     *
     * @param consumerRecord
     * @author ls
     * @date 2021/8/21 20:12
     */
    @KafkaListener(topics = TOPIC_DELETE)
    public void handleDeleteMessage(ConsumerRecord consumerRecord) {
        Event event = checkParseEvent(consumerRecord);
        if (event == null) {
            return;
        }

        // 删除 es 中帖子数据
        elasticsearchService.deleteDiscussPost(event.getEntityId());

    }

    /**
     * 功能描述: <br>
     * 消费发送激活邮件事件
     *
     * @param consumerRecord
     * @author ls
     * @date 2021/8/21 20:12
     */
    @KafkaListener(topics = TOPIC_EMAIL)
    public void handleEmail(ConsumerRecord consumerRecord) {
        Event event = checkParseEvent(consumerRecord);
        if (event == null) {
            return;
        }
        User user = userService.queryUserById(event.getUserId());

        // 发送激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        // http://localhost/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);
    }

    /**
     * 功能描述: <br>
     * 消费分享图片事件
     *
     * @param consumerRecord
     * @author ls
     * @date 2021/8/21 20:12
     */
    @KafkaListener(topics = TOPIC_SHARE)
    public void handleShare(ConsumerRecord consumerRecord) {
        Event event = checkParseEvent(consumerRecord);
        if (event == null) {
            return;
        }
        Map<String, Object> data = event.getData();
        String filename = (String) data.get("filename");
        String htmlUrl = (String) data.get("htmlUrl");
        String suffix = (String) data.get("suffix");
        // 拼接生成图片命令
        String cmd = wkImageCommand + " --quality 75 " + htmlUrl + " " + wkImageStorage + "/" + filename + suffix;
        try {
            // 执行命令
            Runtime.getRuntime().exec(cmd);
            logger.debug("生成长图成功: {}", cmd);
        } catch (IOException e) {
            logger.debug("生成长图失败: {}", e.getMessage());
        }
        // 图片上传到七牛云
        // 启动定时器, 监视该图片, 一旦生成, 则上传至七牛云
        UploadTask task = new UploadTask(filename, suffix);
        Future future = taskScheduler.scheduleAtFixedRate(task, 500);
        task.setFuture(future);
    }

    /**
     * 功能描述: <br>
     * 上传任务
     *
     * @author ls
     * @date 2021/8/28 18:37
     */
    class UploadTask implements Runnable {

        // 文件名
        private String filename;

        // 文件后缀
        private String suffix;

        // 启动任务的返回值
        private Future future;

        // 开始时间
        private long startTime;

        // 上传次数
        private int uploadTimes;

        // 任务最大限制时间
        private static final int MAX_TIME = 30000;

        // 任务限制最大次数
        private static final int MAX_TIMES = 3;

        public UploadTask(String filename, String suffix) {
            this.filename = filename;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
            this.uploadTimes = 1;
        }

        public void setFuture(Future future) {
            this.future = future;
        }

        @Override
        public void run() {
            // 超过最大时间, 生成图片失败
            if (System.currentTimeMillis() - startTime > MAX_TIME) {
                logger.error("执行时间过长, 终止任务: {}", filename);
                // 停止任务
                future.cancel(true);
                return;
            }
            // 超过最大次数, 上传失败
            if (uploadTimes > MAX_TIMES) {
                logger.error("上传次数过多, 终止任务: {}", uploadTimes);
                // 停止任务
                future.cancel(true);
                return;
            }
            // 生成的文件目录
            String path = wkImageStorage + File.separator + filename + suffix;
            File file = new File(path);
            if (file.exists()) {
                logger.info("开始第 [{}] 次上传 [{}]", uploadTimes, filename);
                // 设置相应信息
                StringMap policy = new StringMap();
                policy.put("returnBody", JSON.toJSONString(R.ok()));
                // 生成上传凭证
                Auth auth = Auth.create(accessKey, secretKey);
                String uploadToken = auth.uploadToken(shareBucketName, filename, 3600, policy);
                // 指定上传机房
                UploadManager manager = new UploadManager(new Configuration(Zone.zone2()));
                try {
                    // 开始上传图片
                    Response response = manager.put(path, filename, uploadToken,
                            null, "image/" + suffix.substring(1), false);
                    // 处理相应结果
                    R result = JSON.parseObject(response.bodyString(), R.class);
                    if (result == null || result.getCode() == null ||
                            !Integer.valueOf(200).equals(result.getCode())) {
                        logger.info("第 [{}] 次上传 [{}] 失败", uploadTimes, filename);
                    } else {
                        logger.info("第 [{}] 次上传 [{}] 成功", uploadTimes, filename);
                        // 结束任务
                        future.cancel(true);
                    }
                } catch (QiniuException e) {
                    logger.info("第 [{}] 次上传 [{}] 失败, e.error: {}", uploadTimes, filename, e.error());
                }
                uploadTimes++;
            } else {
                logger.info("等待图片生成 [{}] .", filename);
            }
        }

    }

}
